package com.eqdd.yiqidian.service;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.bean.rebuild.GroupListResultBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Group;
import rx.Observable;
import rx.Subscription;
import rx.schedulers.Schedulers;

import static io.rong.imkit.utils.SystemUtils.getCurProcessName;

/**
 * Created by lvzhihao on 17-4-5.
 */

public class RongyunService extends Service {
    private Subscription subscribe;
    private User user;
    private String token;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        getToken();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private void getToken() {
        user = GreenDaoUtil.getUser();
        if (user != null) {
            token = SPUtil.getToken(user.getGuid());
            if (!TextUtils.isEmpty(token)) {
                System.out.println("使用本地token" + token);
                RongIM.getInstance().disconnect();
                connect(token);
            } else {
                subscribe = Observable.just(1)
                        .observeOn(Schedulers.newThread())
                        .subscribe((i) -> {
                            System.out.println("获取服务器token中。。。");
                            OkGo.<String>post(HttpConfig.BASE_URL + HttpConfig.GET_TOKEN)
                                    .params("userid", user.getGuid())
                                    .params("name", user.getPname())
                                    .params("portraitUri", user.getIphoto())
                                    .execute(new StringCallback() {
                                        @Override
                                        public void onSuccess(Response<String> response) {
                                            String httpResult = response.body();
                                            JsonObject asJsonObject = new JsonParser().parse(httpResult).getAsJsonObject();

                                            if (asJsonObject.get("code").getAsInt() == 200) {
                                                String token = asJsonObject.get("token").getAsString();

                                                if (token != null) {
                                                    System.out.println("获取到token");
                                                    RongIM.getInstance().disconnect();
                                                    connect(token);
                                                }
                                            }
                                        }
                                    });
                        });
            }
        }
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 {@link #)} 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @param
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(final String token) {

        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 * 2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    System.out.println("onTokenIncorrect");
                    SPUtil.saveToken(user.getUname(), "");
                    cancelSubscribe();
                    getToken();
                }

                /**
                 * 连接融云成功
                 *
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    System.out.println("融云###############################连接成功" + userid);
                    SPUtil.saveToken(userid, token);
                    cancelSubscribe();
                    RongIM.getInstance().enableNewComingMessageIcon(true);//显示新消息提醒
                    RongIM.getInstance().enableUnreadMessageIcon(true);//显示未读消息数目
                    OkGo.<HttpResult<List<GroupListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.GROUP_LIST_INFO)
                            .params("userGuid", GreenDaoUtil.getUser().getGuid())
                            .execute(new JsonCallBack<HttpResult<List<GroupListResultBean>>>() {
                                @Override
                                public void onSuccess(Response<HttpResult<List<GroupListResultBean>>> response) {
                                    HttpResult<List<GroupListResultBean>> httpResult = response.body();
                                    if (httpResult.getStatus() == 200) {
                                        GreenDaoUtil.deleteAllGroup();
                                        for (GroupListResultBean groupBean : httpResult.getItems()) {
                                            GreenDaoUtil.insertGroup(groupBean);
                                            Group group = new Group(groupBean.getGroupid(), TextUtils.isEmpty(groupBean.getGroupname()) ? "未命名" : groupBean.getGroupname(), Uri.parse(groupBean.getGroupphoto()));
                                            RongIM.getInstance().refreshGroupInfoCache(group);
                                        }
                                        stopSelf();
                                    }
                                }
                            });

                }

                /**
                 * 连接融云失败
                 *
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    cancelSubscribe();
                    System.out.println("###############################连接失败，" + errorCode);
                    stopSelf();
                }
            });


        }
    }

    private void cancelSubscribe() {
        if (subscribe != null) {
            subscribe.unsubscribe();
        }
    }

}
